package com.shishuo.cms.tag;

import static freemarker.template.ObjectWrapper.BEANS_WRAPPER;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.stereotype.Service;

import com.shishuo.cms.entity.CustomTagHtml;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Service
public class CustomTagHtmlTag extends BaseTagPlugin {

	private static List<String> allTxtPathList = null;

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		String name = (null!=params.get("name"))?params.get("name").toString():null;
		boolean isRandomHtml = (params.get("isRandomHtml") != null) ? Boolean
				.parseBoolean(params.get("isRandomHtml").toString()) : false;
		String keywords = (null!=params.get("keywords"))?params.get("keywords").toString():null;		
		try {
			if (isRandomHtml) {
				String randomHtml = getRandomHtml(keywords);
				env.setVariable("tag_html_value",
						BEANS_WRAPPER.wrap(randomHtml));
			} else {
				CustomTagHtml customTagHtml = customTagHtmlService
						.getByName(name);
				env.setVariable("tag_html_value",
						BEANS_WRAPPER.wrap(customTagHtml));
			}
			body.render(env.getOut());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取随机文章
	 * 
	 * @return
	 */
	private String getRandomHtml(String keywords) {
		if (null == allTxtPathList) {
			allTxtPathList = getAllTxtPath();
		}
		if (null != allTxtPathList) {
			return getRandomHtml(keywords,readTxtFile(allTxtPathList.get( new Random().nextInt(allTxtPathList.size()))));
		}
		return null;
	}
	private String getRandomHtml(String keywords,String txt) {
		StringBuffer retBuffer=new StringBuffer();
		int insertCount= new Random().nextInt(5)+2;
		int beginIndex=0;
		int length=txt.length()/insertCount;
		if(txt.length()>insertCount){
			for (int i = 0; i < insertCount; i++) {
				beginIndex=length*i;
				String tempString=txt.substring(beginIndex,beginIndex+length);
				retBuffer.append(tempString+keywords);
			}
		}
		return retBuffer.toString();
	}
	public static String readTxtFile(String filePath) {
		StringBuffer retString=new StringBuffer();
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					retString.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return retString.toString();
	}

	private List<String> getAllTxtPath() {
		List<String> txtList = new ArrayList<String>();
		String templatePath = getRoot() + "/txt/";
		File dir = new File(templatePath);
		File[] files = dir.listFiles();
		if (null!=files) {
			for (File file : files) {
				if (!file.isDirectory()) {
					txtList.add(file.getAbsolutePath());
				}
			}
			return txtList;
		}
		return null;
	}

	public static String getRoot() {
		String rootKey = "shishuo.cms.root";
		String cmsRoot = System.getProperty(rootKey);
		Enumeration<?> enu = System.getProperties().propertyNames();
		while (enu.hasMoreElements()) {
			Object key = enu.nextElement();
			if (key.toString().startsWith(rootKey)) {
				cmsRoot = System.getProperty(key.toString());
				break;
			}
		}
		return cmsRoot;
	}
}
